/**
 * 此脚本用于更新所有设计模式的示例代码为Java代码
 */
const { MongoClient } = require('mongodb');
require('dotenv').config();

// MongoDB连接配置
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://gof23user:gof23password@localhost:27017/gof23-game';

// 获取不同类型的模式代码
const creationalPatternCodes = require('./patterns/creationalPatternCodes');
const structuralPatternCodes = require('./patterns/structuralPatternCodes');
const behavioralPatternCodes = require('./patterns/behavioralPatternCodes');

// 合并所有模式代码
const allPatternCodes = {
  ...creationalPatternCodes,
  ...structuralPatternCodes,
  ...behavioralPatternCodes
};

async function updateAllPatternCodes() {
  let client;

  try {
    // 连接数据库
    client = new MongoClient(MONGODB_URI);
    await client.connect();
    console.log('MongoDB 连接成功');
    
    const db = client.db(); // 使用默认数据库
    const patternsCollection = db.collection('patterns');
    
    // 获取所有模式
    const patterns = await patternsCollection.find().toArray();
    let updatedCount = 0;
    
    // 遍历更新每个模式的示例代码
    for (const pattern of patterns) {
      if (allPatternCodes[pattern.name]) {
        await patternsCollection.updateOne(
          { _id: pattern._id },
          { $set: { sampleCode: allPatternCodes[pattern.name] } }
        );
        updatedCount++;
        console.log(`成功更新 ${pattern.name} 模式的示例代码`);
      } else {
        console.log(`未找到 ${pattern.name} 模式的示例代码`);
      }
    }
    
    console.log(`共更新了 ${updatedCount} 个设计模式的示例代码`);
  } catch (err) {
    console.error('更新设计模式示例代码失败:', err);
    process.exit(1);
  } finally {
    // 关闭连接
    if (client) {
      await client.close();
    }
    process.exit(0);
  }
}

// 执行更新
updateAllPatternCodes(); 